import json
from utils.log_output import simple_text_log
import os
import requests
import traceback


class ConnectManager:
    def __init__(self):
        # Load configuration
        self.conf_path = os.path.join('config', 'conf.json')

    @property
    def gpu_ip(self):
        hyper_params = json.load(open(self.conf_path, 'rt'))
        return hyper_params['gpu_ip']

    def check_server(self) -> str:
        try:
            r = requests.post(self.gpu_ip+'/check-server')
            r = json.loads(r.text)
            return r['status']
        except Exception as err:
            simple_text_log('error', str(err))
            return 'fail'

    def start_training(self) -> int:
        start_train_url = self.gpu_ip + '/start-server'
        simple_text_log('frontend', 'Sending start-training signal...')

        try:
            r = requests.post(start_train_url).text
            ans = json.loads(r)
            if ans['success'] == 1:
                simple_text_log('frontend', 'Training start...')
                return 0
            else:
                simple_text_log('frontend', f'Training start failed, due to: {ans["msg"]}')
                return 1

        except Exception as err:
            simple_text_log('error', traceback.format_exc())
            return -1

    def stop_training(self) -> int:
        stop_train_url = self.gpu_ip + '/stop-server'
        simple_text_log('frontend', 'Sending stop-training signal...')

        try:
            r = requests.post(stop_train_url).text
            ans = json.loads(r)
            if ans['success'] == 1:
                simple_text_log('frontend', 'Training stop...')
                return 0
            else:
                simple_text_log('frontend', f'Training stop failed, due to: {ans["msg"]}')
                return -1

        except Exception as err:
            simple_text_log('error', traceback.format_exc())
            return -1


if __name__ == '__main__':
    connector = ConnectManager()
    print(connector.stop_training())
